package com.bodacn.packapp;


import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.InputType;
import android.util.DisplayMetrics;
import android.util.Log;
import android.util.TypedValue;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.DataOutputStream;
import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;

import static android.view.View.GONE;
import static android.view.ViewGroup.LayoutParams.MATCH_PARENT;
import static com.bodacn.packapp.DBUtil.QuerySQL2JSON;
import static com.bodacn.packapp.FragmentA.TAG;


/**
 * A simple {@link Fragment} subclass.
 */
public class FragmentPrepBox extends Fragment implements View.OnClickListener {
    private static final int msgScanBarcodeOver=9001;
    private static final int msgGetBoxListOver =9002;
    private static final int msgGetPackListOver=9003;
    private static final int msgGetPackModeOver =9004;
    private static final int MSG_ERROR=9005;
    private static final int msgAheadOver=9006;
    private static final int msgFocusBarcode=9007;
    private static final int msgSizeListHeadOver=9008;
    private static final int msgSizeListDetailOver=9009;
    private static final int msgUnReadyBox=9010;
    ReentrantLock reentrantLock = new ReentrantLock();



    //用于将Activity中的参数传给Fragment
    private Map<String,Object> fragmentParams=new HashMap<String,Object>();
    //用于与主Activity通讯;
    private Handler mainHandler;
    //全局变量
    LinearLayout mainLinerLayout;
    Toast curToast;
    String curDepart,curDepartNo,curLoginUserNo,curLoginUser,curServiceUrl="",
            curTermNo="00000",curServiceDir,CPUID,selectWorkGroup="";
    ImageButton btn_EditBarcode;
    EditText edt_barcode,edt_WorkGroup;
    TextView txt_BoxBarcode,txt_OrderNo, txt_StyleNo,txt_PO, txt_Item,txt_hintinfo,txt_Color,txt_StyleSort;
    TextView txt_IronNum,txt_PackNum, txt_OwenNum,txt_PackMode,txt_BoxArea,txt_NeedNum,txt_UnReadyNum;
    Button btn_Find, btn_Refresh,btn_SelectGroup;
    JSONArray styleSortJSON,resultJSON,departJSON, boxListJSON,packListJSON,packModeJSON,headJSON,unReadyJSON,sizeListHead,sizeListDetail;
    //popwindows
    View root,contentView;
    PopupWindow popupWindow;
    GridView modeList;
    ListView boxList;
    String selBoxBarcode, selSeqNo;
    TextView tv_pop_title;
    LinearLayout templetlisthead;
    ListView lv_Detail;
    String selTaskID="",selBasketID="",selColor="",selSize="",PrBarcode="";
    Socket updateSocket;
    CheckBox chk_OutPrepNum,chk_WholeBox;
    EditText edt_checkReal;
    ListView sizeListView,packList;
    LinearLayout querylisthead;
    //主程序回调传参--------------------------------------------开始;
    private FragmentPrepBoxCallBack mFragmentPrepBoxCallBack;
    /*定义一个业务接口,主程序负责实现，所以需在主程序implements中加上这个接口的引用>>>>>切记<<<<<<
    该Fragment所在Activity需要实现该接口
    该Fragment将通过此接口与它所在的Activity交互*/
    public interface FragmentPrepBoxCallBack {
        // 里面传个值@param Map<String,Object>适应多种类型;
        void FragmentPrepBoxWorkAndTransParams(Map<String, Object> Params);
    }

    //主程序回调传参--------------------------------------------结束;
    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        Activity activity = (Activity) context;
        if (!(activity instanceof FragmentPrepBoxCallBack)) {
            throw new IllegalStateException("MainActivity必须实现FragmentPrepBoxCallBack接口");
        }
        mFragmentPrepBoxCallBack=(FragmentPrepBoxCallBack) activity;
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mFragmentPrepBoxCallBack=null;
    }

    //判断是否为数字，不然不转
    public static boolean isNumeric(String str){
        try {
            new BigDecimal(str);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    public FragmentPrepBox() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //得到Activity的Handler,用于发消息给主Activity;
        MainActivity activity=(MainActivity) getActivity();
        mainHandler=activity.mainHandler;
        //加接口监听
        activity.setTransParamsListenerPrepBox(new MainActivity.OnTransParamsListenerPrepBox() {
            @Override
            public void TransParams(Map<String, Object> mParams) {
                if (mParams!=null) {
                    try {
                        String paramComm= mParams.get("ParamComm").toString();
                        if (paramComm=="LoginParam")
                        {
                            Log.d("FragmentPrepBox","LoginParam------------------>1");
                            //传递登陆参数信息;
                            curLoginUserNo=mParams.get("LoginUserNo").toString();
                            curLoginUser=mParams.get("LoginUser").toString();
                            curServiceUrl=mParams.get("ServiceUrl").toString();
                            curServiceDir=mParams.get("ServiceDir").toString();
                            curDepartNo=mParams.get("DepartNo").toString();
                            curDepart=mParams.get("Depart").toString();
                            CPUID=mParams.get("CPUID").toString();
                            curTermNo=mParams.get("TermNo").toString();
                            //更新当前组别
                            //发消息置焦点
                            Message msg =new Message();
                            msg.what = msgFocusBarcode;
                            fragmentHandler.removeMessages(msg.what);
                            fragmentHandler.sendMessage(msg);
                            edt_WorkGroup.setText(curDepart);
                            Log.d("FragmentE","LoginParam------------------>2");
                        }
                        if ((paramComm=="Barcode")){
                            String barcode=mParams.get("Barcode").toString();
                            edt_barcode.setText(barcode);
                            ExecScanBarcode(edt_barcode);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        root = inflater.inflate(R.layout.fragment_prepbox, container, false);
        contentView = inflater.inflate(R.layout.popselect, container, false);
        InitView(root);
        initPopwindow();
        System.out.println("fragment_e_onCreateView");
        return root;
    }
    //初始化;
    public void InitView(View view){
        chk_OutPrepNum=view.findViewById(R.id.chk_OutPrepNum);
        chk_WholeBox=view.findViewById(R.id.chk_WholeBox);
        mainLinerLayout=view.findViewById(R.id.mainLinerLayout);
        sizeListView=view.findViewById(R.id.sizeListView);
        querylisthead=view.findViewById(R.id.querylisthead);
        modeList =view.findViewById(R.id.modeList);
        packList=view.findViewById(R.id.packList);
        boxList=view.findViewById(R.id.boxList);
        boxList.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                try {
                    selBoxBarcode=boxListJSON.optJSONObject(position).getString("BoxNo");
                    selSeqNo =boxListJSON.optJSONObject(position).getString("SeqNo");
                    showaPopmenu();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                return false;

            }
        });
        txt_StyleSort=view.findViewById(R.id.txt_StyleSort);
        txt_Color=view.findViewById(R.id.txt_Color);
        txt_IronNum=view.findViewById(R.id.txt_IronNum);
        txt_PackNum=view.findViewById(R.id.txt_PackNum);
        txt_OwenNum=view.findViewById(R.id.txt_OwenNum);
        //界面Edit;
        edt_barcode=(EditText)view.findViewById(R.id.edt_barcode);
        edt_barcode.setInputType(InputType.TYPE_NULL);
        edt_barcode.setFocusable(true);
        edt_barcode.setFocusableInTouchMode(true);
        edt_barcode.requestFocus();
        edt_barcode.requestFocusFromTouch();
        view.findViewById(R.id.btn_Query).setOnClickListener(this);
        //别的功能键
        btn_EditBarcode=(ImageButton)view.findViewById(R.id.btn_EditBarcode);
        btn_EditBarcode.setOnClickListener(this);
        btn_EditBarcode.setFocusable(false);
        btn_EditBarcode.setFocusableInTouchMode(false);
        //界面Text;
        txt_BoxBarcode=(TextView) view.findViewById(R.id.txt_BoxBarcode);
        txt_OrderNo=(TextView) view.findViewById(R.id.txt_OrderNo);
        txt_StyleNo =(TextView) view.findViewById(R.id.txt_StyleNo);
        txt_PO=(TextView)view.findViewById(R.id.txt_PO);
        txt_Item =(TextView) view.findViewById(R.id.txt_Item);
        txt_hintinfo=(TextView) view.findViewById(R.id.txt_hintinfo);
        txt_UnReadyNum=(TextView) view.findViewById(R.id.txt_UnReadyNum);
        txt_NeedNum=(TextView) view.findViewById(R.id.txt_NeedNum);
        txt_PackMode =(TextView) view.findViewById(R.id.txt_PackMode);
        txt_BoxArea =(TextView) view.findViewById(R.id.txt_BoxArea);
        edt_WorkGroup=view.findViewById(R.id.edt_WorkGroup);
        btn_Find= view.findViewById(R.id.btn_Find);
        btn_Find.setOnClickListener(this);
        btn_SelectGroup=view.findViewById(R.id.btn_SelectGroup);
        btn_SelectGroup.setOnClickListener(this);
        btn_Refresh=view.findViewById(R.id.btn_Refresh);
        btn_Refresh.setOnClickListener(this);
        view.findViewById(R.id.btn_selectStyleSort).setOnClickListener(this);
        view.findViewById(R.id.btn_aheadOver).setOnClickListener(this);
        view.findViewById(R.id.btn_unReadyBox).setOnClickListener(this);
        //初始提醒;
        curToast = Toast.makeText(getActivity(), "", Toast.LENGTH_SHORT);

    }

    // 隐藏手机键盘
    private void hideIM(View edt) {
        try {
            InputMethodManager im = (InputMethodManager) getActivity().getSystemService(Activity.INPUT_METHOD_SERVICE);
            IBinder windowToken = edt.getWindowToken();
            if (windowToken != null) {
                im.hideSoftInputFromWindow(windowToken, 0);
            }
        } catch (Exception e) {

        }
    }

    @Override
    public void onClick(View v) {
        hideIM(v);
        switch (v.getId()){
            case R.id.view_oneBtn:
            case R.id.view_twoBtn:
            case R.id.view_threeBtn:
            case R.id.view_fourBtn:
            case R.id.view_fiveBtn:
            case R.id.view_sixBtn:
            case R.id.view_sevenBtn:
            case R.id.view_eightBtn:
            case R.id.view_nineBtn:
            case R.id.view_zeroBtn:
                Button tmpBtn1 = v.findViewById(v.getId());
                edt_checkReal.getText().append(tmpBtn1.getText());
                break;
            case R.id.view_delBtn:
                if (edt_checkReal.getText().length() > 0) {
                    edt_checkReal.setSelection(edt_checkReal.getText().length());
                    int start = edt_checkReal.getSelectionStart();
                    edt_checkReal.getText().delete(start - 1, start);
                }
                break;
            case R.id.view_clearBtn:
                edt_checkReal.setText("");
                break;
            case R.id.btn_AffirmCall:
                if (edt_checkReal.getText().length()>0){
                    searchBarcodeData(PrBarcode,edt_checkReal.getText().toString());
                }
                break;
            case R.id.btn_selectStyleSort:
                showSelectStyleSort();
                break;
            case R.id.btn_PausePack:
                transBoxInfo("PauseBox");
                break;
            case R.id.btn_ClearPack:
                transBoxInfo("ClearBox");
                break;
            case R.id.btn_Refresh:
                GetSizeList("SizeListHead");
                GetPackMode();
                break;
            case R.id.btn_SelectGroup:
                btn_SelectGroup.setEnabled(false);
                showSelectGroup();
                break;
            case R.id.btn_Find:
                if (edt_barcode.getText().length()==0) {
                    curToast.setText("请先输入条码!");
                    curToast.show();
                } else ExecScanBarcode(edt_barcode);
                break;
            case R.id.btn_EditBarcode:
                edt_barcode.setInputType(InputType.TYPE_CLASS_NUMBER);
                edt_barcode.setFocusable(true);
                edt_barcode.setFocusableInTouchMode(true);
                edt_barcode.requestFocus();
                edt_barcode.requestFocusFromTouch();
                //1.得到InputMethodManager对象
                InputMethodManager imm = (InputMethodManager) getActivity().getSystemService(getActivity().INPUT_METHOD_SERVICE);
                //2.调用showSoftInput方法显示软键盘，其中view为聚焦的view组件
                imm.showSoftInput(edt_barcode,InputMethodManager.SHOW_FORCED);
                break;
            case R.id.btn_aheadOver:
                if (txt_BoxBarcode.getText().toString().length()>0) showaheadOver();
                else {
                    curToast.setText("请先扫描包装箱条码!");
                    curToast.show();
                }
                break;

            case R.id.btn_unReadyBox:
                showunReadyBox();
                break;
            case R.id.btn_Query:
                Intent outIntent=new Intent(getContext(),QueryActivity.class);
                Bundle paramBundle=new Bundle();
                paramBundle.clear();
                paramBundle.putString("LoginUserNo", curLoginUserNo);
                paramBundle.putString("LoginUser",curLoginUser);
                paramBundle.putString("CurDepartNo",curDepartNo);
                paramBundle.putString("CurDepart",curDepart);
                paramBundle.putString("CPUID",CPUID);
                paramBundle.putString("QueryTitle", "预装箱查询");
                paramBundle.putString("ManuDepart",edt_WorkGroup.getText().toString());
                paramBundle.putString("OrderNo",txt_OrderNo.getText().toString());
                paramBundle.putString("StyleNo",txt_StyleNo.getText().toString());
                paramBundle.putString("StyleSort",txt_StyleSort.getText().toString());
                paramBundle.putString("NeedOrder","NO");
                paramBundle.putString("NeedDate","NO");
                outIntent.putExtras(paramBundle);
                startActivity(outIntent);
                break;
            default:
                break;
        }
    }
    private void showunReadyBox(){
        //先显示对话框,再调用查询加载
        initPopwindow();
        try {
            unReadyJSON=new JSONArray("[]");
            headJSON = new JSONArray("[{\"TitleName\":\"OrderNo\",\"TitleText\":\"合约号\",\"TxtSize\":17,\"TxtWidth\":200,\"AutoZoom\":0,\"Align\":0,\"Color\":\"Main\"}," +
                    "{\"TitleName\":\"StyleSort\",\"TitleText\":\"款式\",\"TxtSize\":17,\"TxtWidth\":80,\"AutoZoom\":1,\"Align\":0,\"Color\":\"Main\"},"+
                    "{\"TitleName\":\"PO\",\"TitleText\":\"PO号\",\"TxtSize\":17,\"TxtWidth\":110,\"AutoZoom\":1,\"Align\":0,\"Color\":\"Main\"},"+
                    "{\"TitleName\":\"BoxBarcode\",\"TitleText\":\"箱号\",\"TxtSize\":17,\"TxtWidth\":170,\"AutoZoom\":1,\"Align\":0,\"Color\":\"Main\"},"+
                    "{\"TitleName\":\"Color\",\"TitleText\":\"色组\",\"TxtSize\":17,\"TxtWidth\":85,\"AutoZoom\":0,\"Align\":0,\"Color\":\"Main\"},"+
                    "{\"TitleName\":\"Size\",\"TitleText\":\"尺码\",\"TxtSize\":17,\"TxtWidth\":75,\"AutoZoom\":0,\"Align\":0,\"Color\":\"Main\"},"+
                    "{\"TitleName\":\"SewSize\",\"TitleText\":\"缝制尺码\",\"TxtSize\":17,\"TxtWidth\":120,\"AutoZoom\":0,\"Align\":0,\"Color\":\"Main\"},"+
                    "{\"TitleName\":\"NeedNum\",\"TitleText\":\"件数\",\"TxtSize\":17,\"TxtWidth\":75,\"AutoZoom\":0,\"Align\":0,\"Color\":\"Main\"},"+
                    "{\"TitleName\":\"ScanNum\",\"TitleText\":\"已装\",\"TxtSize\":17,\"TxtWidth\":75,\"AutoZoom\":0,\"Align\":0,\"Color\":\"Main\"},"+
                    "{\"TitleName\":\"OwenNum\",\"TitleText\":\"差数\",\"TxtSize\":17,\"TxtWidth\":75,\"AutoZoom\":0,\"Align\":0,\"Color\":\"Main\"},"+
                    "{\"TitleName\":\"Place\",\"TitleText\":\"位置\",\"TxtSize\":17,\"TxtWidth\":80,\"AutoZoom\":0,\"Align\":0,\"Color\":\"Main\"}]");
        } catch (JSONException jSONException) {
            jSONException.printStackTrace();
        }
        tv_pop_title.setText("未满箱信息");
        contentView.findViewById(R.id.linear_pop_search).setVisibility(GONE);
        contentView.findViewById(R.id.btn_pop_cancel).setVisibility(GONE);
        CreateListHead();
        lv_Detail.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> param1AdapterView, View view, int postion, long param1Long) {
                try {
                    JSONObject jsonObject=unReadyJSON.optJSONObject(postion);
                    if (jsonObject.has("BoxBarcode")) edt_barcode.setText(jsonObject.getString("BoxBarcode"));
                    ExecScanBarcode(edt_barcode);
                    if (popupWindow != null && popupWindow.isShowing())
                    popupWindow.dismiss();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        //控制屏幕宽度
        int deviationX=1200,deviationY=650;
        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        System.out.println("屏宽:" + dm.widthPixels);
        System.out.println("屏高:" + dm.heightPixels);
        popupWindow.setWidth(dp2px(deviationX));
        popupWindow.setHeight(dp2px(deviationY));
        popupWindow.showAtLocation(mainLinerLayout, Gravity.CENTER,0,0);
        //加载默认的历史合约;
        SearchunReadyBox();
    }

    //过滤订单
    private void SearchunReadyBox() {
        try {
            unReadyJSON=new JSONArray("[]");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //执行SQL过程
        String SqlComm="Exec KeyPoint_Pack_PrepUnReadyBox  @OperType='unReadyBox',@TermNO='" + curTermNo + "',@ManuWorkGroup='" + edt_WorkGroup.getText().toString()
                + "',@WorkGroup='" + curDepart+ "',@OrderNo='" + txt_OrderNo.getText().toString()+"',@UserNo='"+curLoginUserNo+"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);

    }

    private void showaheadOver(){
        //创建布局
        LayoutInflater inflater=getActivity().getLayoutInflater();
        final View proc_popmenu=inflater.inflate(R.layout.fragment_e_popmenu, null);
        //Activity.findViewById最终还是会调用View.findViewById
        //因为在Activity的onCreate中一定会先setContentView的
        final Button btn_ProcMenu_TypeA=(Button)proc_popmenu.findViewById(R.id.btn_ProcMenu_TypeA);
        final Button btn_ProcMenu_TypeB=(Button)proc_popmenu.findViewById(R.id.btn_ProcMenu_TypeB);
        final Button btn_ProcMenu_TypeC=(Button)proc_popmenu.findViewById(R.id.btn_ProcMenu_TypeC);
        final Button btn_ProcMenu_TypeD=(Button)proc_popmenu.findViewById(R.id.btn_ProcMenu_TypeD);
        //创建对话框
        final AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setView(proc_popmenu).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Log.v("tag","取消");
            }
        });
        final Dialog dialog = builder.show();
        WindowManager m = getActivity().getWindowManager();
        Display d = m.getDefaultDisplay();  //为获取屏幕宽、高
        android.view.WindowManager.LayoutParams p = dialog.getWindow().getAttributes();  //获取对话框当前的参数值
        p.height = dp2px(400);   //高度设置为屏幕的0.3
        p.width = dp2px(400);    //宽度设置为屏幕的0.5
        dialog.getWindow().setAttributes(p);     //设置生效
        btn_ProcMenu_TypeA.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                transaheadOver("印绣花出疵");
                dialog.dismiss();
            }
        });
        btn_ProcMenu_TypeB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                transaheadOver("裁剪出疵");
                dialog.dismiss();
            }
        });
        btn_ProcMenu_TypeC.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                transaheadOver("车缝出疵");
                dialog.dismiss();
            }
        });
        btn_ProcMenu_TypeD.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                transaheadOver("发烫未齐");
                dialog.dismiss();
            }
        });
    }

    //刷新缸布列表;
    private void transaheadOver(String issue)
    {
        //执行SQL过程
        String SqlComm="Exec KeyPoint_Pack_PrepAheadOver @OperType='AheadOver',@BoxBarcode='"+txt_BoxBarcode.getText().toString()
                +"',@Issue='"+issue+"',@ManuWorkGroup='" +edt_WorkGroup.getText().toString()+"',@UserNo='"+curLoginUserNo+"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }

    //刷新缸布列表;
    private void transBoxInfo(String paramTransType)
    {
        //执行SQL过程
        String SqlComm="Exec KeyPoint_Pack_PrepScan @OperType='"+paramTransType+"',@Barcode='',@BoxBarcode='"+txt_BoxBarcode.getText().toString()
                +"',@ManuWorkGroup='" +edt_WorkGroup.getText().toString()
                +"',@TaskID='"+selTaskID+"',@Color='"+selColor+"',@Size='"+selSize
                +"',@UserNo='"+curLoginUserNo+"',@TermNo='"+curTermNo+"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }

    //显示工序选择
    private void showSelectGroup(){
        if (departJSON ==null||departJSON.length()==0){
            curToast.setText("没有组部信息,正在刷新稍后再试...");
            curToast.show();
            refreshDepartData();
            return;
        }
        selectWorkGroup="";
        //创建布局
        LayoutInflater inflater=getActivity().getLayoutInflater();
        final View select_proc=inflater.inflate(R.layout.select_workgroup, null);

        //Activity.findViewById最终还是会调用View.findViewById
        //因为在Activity的onCreate中一定会先setContentView的
        final GridView selectGrid=(GridView)select_proc.findViewById(R.id.selectGrid);
        final SelectGridAdapter selectGridAdapter=new SelectGridAdapter(getContext());
        selectGrid.setAdapter(selectGridAdapter);
        selectGrid.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                try {
                    selectWorkGroup=departJSON.getJSONObject(position).getString("Department");
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }
        });
        //创建对话框
        AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setView(select_proc).setPositiveButton("确定", new DialogInterface.OnClickListener(){
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Field field = null;
                        if (selectWorkGroup.length()>0) {
                            try {
                                field = dialog.getClass().getSuperclass().getDeclaredField( "mShowing" );
                                field.setAccessible(true );
                                field.set(dialog,true );
                            } catch (NoSuchFieldException e) {
                                e.printStackTrace();
                            }
                            catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                            //置当前工序名称;
                            edt_WorkGroup.setText(selectWorkGroup);
                        } else {
                            try {
                                field = dialog.getClass().getSuperclass().getDeclaredField( "mShowing" );
                                field.setAccessible(true );
                                field.set( dialog,false );
                            } catch (NoSuchFieldException e) {
                                e.printStackTrace();
                            }
                            catch (IllegalAccessException e) {
                                e.printStackTrace();
                            }
                            curToast.setText("请通过点击选中需要切换的组别！");
                            curToast.show();
                        }
                    }
                }
        ).setNeutralButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Log.v("tag","取消");
            }
        }).setTitle("组别选择");
        final AlertDialog dialog =builder.create();
        dialog.show();
        WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
        params.width = 800;
        params.height = 500 ;
        dialog.getWindow().setAttributes(params);
        btn_SelectGroup.setEnabled(true);
    }
    //刷新订单初始化列表;
    private void refreshDepartData()
    {
        try {
            departJSON=new JSONArray("[]");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String SqlComm="Exec KeyPoint_Pack_GetDepart @TermNo='" + curTermNo + "',@WorkGroup='" + edt_WorkGroup.getText().toString() + "',@UserNo='"+curLoginUserNo+"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);

    }

    //订单表格适配器;
    public final class SelectGridAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public SelectGridAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return departJSON.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return departJSON.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) convertView = inflater.inflate(R.layout.select_workgroup_item, null, false);
            convertView.setLayoutParams(new GridView.LayoutParams((int)140,(int)(50)));
            convertView.setBackground(getResources().getDrawable(R.drawable.row_selector));
            try {
                TextView tv = (TextView) convertView.findViewById(R.id.text_selgroup_name);// 显示文字
                if (departJSON.optJSONObject(0).has("Department")==true)
                    tv.setText(departJSON.optJSONObject(position).get("Department").toString());
            } catch (JSONException e) {
                e.printStackTrace();
                curToast.setText(e.getMessage());
                curToast.show();
            }
            return convertView;
        }
    }

    private void ExecScanBarcode(View v)
    {
        //隐藏键盘
        edt_barcode.setInputType(InputType.TYPE_NULL);
        hideIM(v);
        if (edt_barcode.getText().toString().length() == 0) {
            curToast.setText("请先输入条码!");
            curToast.show();
            return;
        }
        searchBarcodeData(edt_barcode.getText().toString(),"1");
        if (edt_barcode != null) {
            edt_WorkGroup.setFocusable(false);
            edt_WorkGroup.setFocusableInTouchMode(false);
            edt_barcode.setText("");
            edt_barcode.selectAll();
        }
    }
    //刷新缸布列表;
    private void searchBarcodeData(String BarcodeParam,String PieceNum)
    {
        try {
            resultJSON =new JSONArray("[]");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        String tj="";
        if (chk_OutPrepNum.isChecked()) tj=",@OutPrepNum=1";
        if (chk_WholeBox.isChecked()) tj=",@WholeBoxScan=1";

        //执行SQL过程
        String SqlComm="Exec KeyPoint_Pack_PrepScan @OperType='ScanBarcode',@Barcode='" + BarcodeParam
                + "',@BoxBarcode='"+txt_BoxBarcode.getText().toString()+"',@ManuWorkGroup='" +edt_WorkGroup.getText().toString()
                +"',@OrderNo='"+txt_OrderNo.getText().toString()+"',@StyleNo='"+txt_StyleNo.getText().toString()
                +"',@StyleSort='"+txt_StyleSort.getText().toString()+"',@PO='"+txt_PO.getText().toString()
                +"',@TaskID='"+selTaskID+"',@Color='"+selColor+"',@Size='"+selSize
                +"',@UserNo='"+curLoginUserNo+"',@TermNo='"+curTermNo+"',@PieceNum='"+PieceNum+"'"+tj;
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }

    //直接连获取数据，与Handler配套使用;
    private synchronized void ReadSQLData(final String SQLComm) {
        System.out.println("SQLComm:"+SQLComm);
        Runnable run = new Runnable() {
            @Override
            public synchronized void run() {
                try{
                    System.out.println("run--Start");
                    reentrantLock.lock();
                    System.out.println("run--1");
                    JSONArray jsonArray  = QuerySQL2JSON(SQLComm);
                    System.out.println(jsonArray);
                    System.out.println("run--2");
                    Message msg = new Message();
                    String OperType="";
                    //往界面转数据;
                    if ((jsonArray!=null)&&(jsonArray.length()>0)) {
                        if (jsonArray.optJSONObject(0).has("OperType"))
                            OperType=jsonArray.optJSONObject(0).getString("OperType");
                        if (jsonArray.optJSONObject(0).has("OPERTYPE"))
                            OperType=jsonArray.optJSONObject(0).getString("OPERTYPE");
                        if (OperType.length()>0) {
                            if (OperType.equals("ScanBarcode")||OperType.equals("PauseBox")||OperType.equals("ClearBox")||OperType.equals("BoxTrans")) {
                                resultJSON = jsonArray;
                                msg.what = msgScanBarcodeOver;
                                fragmentHandler.removeMessages(msg.what);
                                fragmentHandler.sendMessage(msg);
                            } else if (OperType.equals("DepartList")){
                                departJSON=jsonArray;
                            } else if (OperType.equals("PackMode")) {
                                packModeJSON =jsonArray;
                                msg.what = msgGetPackModeOver;
                                fragmentHandler.removeMessages(msg.what);
                                fragmentHandler.sendMessage(msg);
                            } else if (OperType.equals("BoxList")){
                                boxListJSON =jsonArray;
                                msg.what = msgGetBoxListOver;
                                fragmentHandler.removeMessages(msg.what);
                                fragmentHandler.sendMessage(msg);
                            }else if (OperType.equals("PackList")){
                                packListJSON =jsonArray;
                                msg.what = msgGetPackListOver;
                                fragmentHandler.removeMessages(msg.what);
                                fragmentHandler.sendMessage(msg);
                            }else if (OperType.equals("unReadyBox")) {
                                unReadyJSON=jsonArray;
                                msg.what = msgUnReadyBox;
                                fragmentHandler.removeMessages(msg.what);
                                fragmentHandler.sendMessage(msg);
                            } else if (OperType.equals("AheadOver")) {
                                resultJSON=jsonArray;
                                msg.what = msgAheadOver;
                                fragmentHandler.removeMessages(msg.what);
                                fragmentHandler.sendMessage(msg);
                            }else if (OperType.equals("SizeListHead")) {
                                sizeListHead=jsonArray;
                                msg.what = msgSizeListHeadOver;
                                fragmentHandler.removeMessages(msg.what);
                                fragmentHandler.sendMessage(msg);
                            }else if (OperType.equals("SizeListDetail")) {
                                sizeListDetail=jsonArray;
                                msg.what = msgSizeListDetailOver;
                                fragmentHandler.removeMessages(msg.what);
                                fragmentHandler.sendMessage(msg);
                            }
                        }
                        if (jsonArray.optJSONObject(0).has("TypeGroup")==true) {
                            departJSON = jsonArray;
                        }
                        if (jsonArray.optJSONObject(0).has("SQLExcept") == true) {
                            //刷新界面;
                            Message errmsg = new Message();
                            Bundle bundle=new Bundle();
                            bundle.putString("HintInfo",jsonArray.optJSONObject(0).getString("SQLMessage"));
                            errmsg.what = MSG_ERROR;
                            errmsg.setData(bundle);
                            fragmentHandler.removeMessages(errmsg.what);
                            fragmentHandler.sendMessage(errmsg);
                        }
                    } else {
                        //刷新界面;
                        Message errmsg = new Message();
                        Bundle bundle=new Bundle();
                        bundle.putString("HintInfo","未返回任何数据!");
                        errmsg.what = MSG_ERROR;
                        errmsg.setData(bundle);
                        fragmentHandler.removeMessages(errmsg.what);
                        fragmentHandler.sendMessage(errmsg);
                    };
                    reentrantLock.unlock();
                    System.out.println("run--3");
                } catch (Exception e) {
                    //刷新界面;
                    Message errmsg = new Message();
                    Bundle bundle=new Bundle();
                    bundle.putString("HintInfo",e.getMessage());
                    errmsg.what = MSG_ERROR;
                    errmsg.setData(bundle);
                    fragmentHandler.removeMessages(errmsg.what);
                    fragmentHandler.sendMessage(errmsg);
                    reentrantLock.unlock();
                }
            }

        };
        new Thread(run).start();

    }


    private void showaPopmenu(){
        //创建布局
        LayoutInflater inflater=getActivity().getLayoutInflater();
        final View proc_popmenu=inflater.inflate(R.layout.fragment_prepbox_popmenu, null);
        //Activity.findViewById最终还是会调用View.findViewById
        //因为在Activity的onCreate中一定会先setContentView的
        final Button btn_ProcMenu_TypeA=(Button)proc_popmenu.findViewById(R.id.btn_ProcMenu_TypeA);
        final Button btn_ProcMenu_TypeB=(Button)proc_popmenu.findViewById(R.id.btn_ProcMenu_TypeB);
        //创建对话框
        final AlertDialog.Builder builder = new AlertDialog.Builder(getContext());
        builder.setView(proc_popmenu).setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Log.v("tag","取消");
            }
        });
        final Dialog dialog = builder.show();
        WindowManager m = getActivity().getWindowManager();
        Display d = m.getDefaultDisplay();  //为获取屏幕宽、高
        WindowManager.LayoutParams p = dialog.getWindow().getAttributes();  //获取对话框当前的参数值
        p.height = dp2px(250);   //高度设置为屏幕的0.3
        p.width = dp2px(400);    //宽度设置为屏幕的0.5
        dialog.getWindow().setAttributes(p);     //设置生效
        btn_ProcMenu_TypeA.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                transPopmenu("Delete",selBoxBarcode, selSeqNo);
                dialog.dismiss();
            }
        });
        btn_ProcMenu_TypeB.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //发送数据给盛元成
                sendDataSYC(selBoxBarcode);
                dialog.dismiss();
            }
        });

    }

    //发送数据给盛元成;
    private void sendDataSYC(final String boxBarcode) {
        //线程调用过程;
        Runnable run = new Runnable() {
            @Override
            public void run() {
                String SqlComm;
                String AffirmProcID = java.util.UUID.randomUUID().toString();
                //将数据读到JSONArray;
                try {
                    updateSocket = new Socket("10.10.22.196", 30001);
                    //updateSocket = new Socket("192.168.199.186", 30000);
                    DataOutputStream dout =new DataOutputStream(updateSocket.getOutputStream());
                    System.out.println("saveData:"+1);
                    JSONArray info=QuerySQL2JSON("Exec AutoBoxGetBasketInfo @BasketID='"+boxBarcode+"'");
                    JSONArray clothData=QuerySQL2JSON("Exec AutoBoxGetBasketClothData @BasketID='"+boxBarcode+"'");
                    JSONArray markRule=QuerySQL2JSON("Exec AutoBoxGetBasketMarkRule @BasketID='"+boxBarcode+"'");
                    JSONArray labelRule=QuerySQL2JSON("Exec AutoBoxGetBasketLabelRule @BasketID='"+boxBarcode+"'");
                    JSONObject jsonObject=info.optJSONObject(0);
                    jsonObject.put("clothData",clothData);
                    jsonObject.put("markRule",markRule);
                    jsonObject.put("labelRule",labelRule);
                    System.out.println(jsonObject.toString());
                    //发送数据
                    dout.writeUTF(jsonObject.toString());
                    dout.flush();
                    Thread.sleep(50, 0);
                } catch (Exception e){
                    //刷新界面;
                    Message errmsg = new Message();
                    Bundle bundle=new Bundle();
                    bundle.putString("HintInfo",e.getMessage());
                    errmsg.what = MSG_ERROR;
                    errmsg.setData(bundle);
                    fragmentHandler.removeMessages(errmsg.what);
                    fragmentHandler.sendMessage(errmsg);
                } finally {
                    //准备接收数据;
                    System.out.println("准备接收数据");
                    /*
                    try {


                        DataInputStream din = new DataInputStream(updateSocket.getInputStream());
                        ByteArrayOutputStream baos = new ByteArrayOutputStream();
                        String JsonStr = null;
                        byte[] by = new byte[2048];
                        int n;
                        while ((n = din.read(by)) != -1)
                        {
                            baos.write(by, 0, n);
                        }
                        JsonStr = new String(baos.toByteArray(),"utf-8");
                        System.out.println("盛元成返回:"+JsonStr);
                        //刷新界面;
                        Message errmsg = new Message();
                        Bundle bundle=new Bundle();
                        bundle.putString("HintInfo",JsonStr);
                        errmsg.what = MSG_ERROR;
                        errmsg.setData(bundle);
                        fragmentHandler.removeMessages(errmsg.what);
                        fragmentHandler.sendMessage(errmsg);

                    } catch (IOException e) {
                        e.printStackTrace();
                    }


                     */

                }

            }
        };
        new Thread(run).start();

    }

    private void transPopmenu(String transType, String paramBoxBarcode, String paramSeqNo) {
        //执行SQL过程
        String SqlComm="Exec KeyPoint_Pack_PrepBoxTrans  @OperType='BoxTrans',@TermNO='" + curTermNo
                + "',@ManuWorkGroup='" + edt_WorkGroup.getText().toString()+ "',@WorkGroup='" + curDepart
                +"',@TransType='" + transType+ "',@BoxBarcode='" + paramBoxBarcode+ "',@SeqNo='" + paramSeqNo
                +"',@UserNo='"+curLoginUserNo+"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);
    }


    /**
     * 定义一个Handler用于接收Fragment发出来的指令
     */
    public Handler fragmentHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg!=null){
                System.out.println("收到的消息是："+msg.what);
                //任意消息来均置焦点
                setEditBarcodeFocus();
                btn_SelectGroup.setEnabled(true);
                int msgId = msg.what;
                switch (msgId) {
                    case msgGetPackListOver:
                        //准备显示明细
                        PackListAdapter packListAdapter = new PackListAdapter(getContext());
                        packList.setAdapter(packListAdapter);
                        break;
                    case msgSizeListHeadOver:
                        //创建表头
                        CreateSizeListHead();
                        GetSizeList("SizeListDetail");
                        break;
                    case msgSizeListDetailOver:
                        //准备显示明细
                        SizeListAdapter sizeListAdapter = new SizeListAdapter(getContext());
                        sizeListAdapter.selectJSON=sizeListDetail;
                        sizeListView.setAdapter(sizeListAdapter);
                        break;
                    case msgFocusBarcode:
                        setEditBarcodeFocus();
                        break;
                    case MSG_ERROR:
                        Bundle bundle=msg.getData();
                        curToast.setText(bundle.getString("HintInfo"));
                        curToast.show();
                        break;
                    case msgScanBarcodeOver:
                        //显示预排单;
                        fillFormtext();
                        break;
                    case msgGetBoxListOver:
                        //准备显示明细
                        BoxListAdapter boxListAdapter = new BoxListAdapter(getContext());
                        boxList.setAdapter(boxListAdapter);
                        break;
                    case msgGetPackModeOver:
                        ModeListAdapter modeListAdapter = new ModeListAdapter(getContext());
                        modeList.setAdapter(modeListAdapter);
                        GetBoxList();
                        break;
                    case msgUnReadyBox:
                        //准备显示明细
                        SelectTempletListAdapter selectTempletListAdapter1 = new SelectTempletListAdapter(getContext());
                        selectTempletListAdapter1.selectJSON=unReadyJSON;
                        lv_Detail.setAdapter(selectTempletListAdapter1);
                        break;
                    case msgAheadOver:
                        fillFormtext();
                        break;
                    default:
                        break;
                }
            }
        }
    };


    //设置焦点到扫描输入框
    private void setEditBarcodeFocus()
    { //传消息给主界面;
        if (mFragmentPrepBoxCallBack!=null)
        {
            fragmentParams.clear();
            fragmentParams.put("ParamComm","AllowScan");//命令;
            fragmentParams.put("ParamValue","Y");//参数;
            mFragmentPrepBoxCallBack.FragmentPrepBoxWorkAndTransParams(fragmentParams);
        } else Log.d("msg","mFragmentECallBack-----------空的咋办");
        //设置焦点
        System.out.println(this.getClass().getName()+" 设置焦点-------------------------------1.Start");
        if (edt_barcode!=null) {
            edt_barcode.selectAll();
            edt_barcode.setFocusable(true);
            edt_barcode.setFocusableInTouchMode(true);
            edt_barcode.requestFocus();
            edt_barcode.requestFocusFromTouch();
            hideIM(getView());
        }
        System.out.println(this.getClass().getName()+" 设置焦点-------------------------------1.End");
    }

    //数据适配器，继承自BaseAdapter;
    private final class SelectTempletListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        private JSONArray selectJSON;
        public SelectTempletListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        public  String TrnasValue(String params)
        {
            if ((params.toUpperCase()=="NULL".toUpperCase())||(params=="0")||(params=="0.0"))
                return "";
            else return params;
        }
        @Override
        public int getCount() {
            //每页行数
            return selectJSON.length();
        }
        @Override
        public Object getItem(int position) {
            try {
                if (position<selectJSON.length())
                    return selectJSON.getJSONArray(position);
                else
                    return null;
            } catch (JSONException e)
            {
                e.printStackTrace();
                System.out.println("getItem取JSON数据出错!");
                return  null;
            }
        }
        @Override
        public long getItemId(int position) {
            return position;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = inflater.inflate(R.layout.popselect_item, null, false);
            int pullVatListWidth=parent.getWidth();
            view.setLayoutParams(new ListView.LayoutParams((int)pullVatListWidth,dp2px(45)));
            //转换分页码;
            int curPosition= position;
            String tmpValue;
            int color = getResources().getColor(R.color.text_black);
            if (curPosition<selectJSON.length()) {
                try {
                    Log.d(TAG, "getView()----------------------------------------------------->" + position);
                    if (selectJSON.optJSONObject(curPosition).has("ConColor") == true) {
                        tmpValue = selectJSON.optJSONObject(curPosition).getString("ConColor");
                        color=GetColorValue(tmpValue);
                    }
                    for (int i = 0; i < headJSON.length(); i++)
                        if (headJSON.optJSONObject(i).has("TitleText") == true) {
                            try {
                                String TitleName = headJSON.optJSONObject(i).getString("TitleName");
                                if (selectJSON.optJSONObject(curPosition).has(TitleName)==true) tmpValue= selectJSON.optJSONObject(curPosition).getString(TitleName);
                                else tmpValue="unReturn";
                                int TxtSize = headJSON.optJSONObject(i).getInt("TxtSize");
                                float txtWidth = headJSON.optJSONObject(i).getLong("TxtWidth");
                                int AutoZoom = headJSON.optJSONObject(i).getInt("AutoZoom");
                                TextView tv = new TextView(view.getContext());
                                tv.setText(TrnasValue(tmpValue));
                                tv.setWidth((int) txtWidth);
                                tv.setTextColor(color);
                                tv.setGravity(Gravity.CENTER_VERTICAL);
                                if (headJSON.optJSONObject(i).has("Align")==true) {
                                    int Align;
                                    Align = headJSON.optJSONObject(i).getInt("Align");
                                    switch (Align) {
                                        case 0:
                                            tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
                                            break;
                                        case 1:
                                            tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
                                            break;
                                        case 2:
                                            tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.RIGHT);
                                            break;
                                        default:
                                            tv.setGravity(Gravity.CENTER_VERTICAL);
                                            break;
                                    }
                                }
                                tv.setTextSize(TxtSize);
                                //添加到View中;
                                if (AutoZoom == 1)
                                    ((LinearLayout)view).addView(tv, new LinearLayout.LayoutParams((int) txtWidth, MATCH_PARENT, 1));
                                else ((LinearLayout)view).addView(tv);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
            return view;
        }
    }


    //数据适配器，继承自BaseAdapter;
    private final class SizeListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        private JSONArray selectJSON;
        public SizeListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        public  String TrnasValue(String params)
        {
            if ((params.toUpperCase()=="NULL".toUpperCase())||(params=="0")||(params=="0.0"))
                return "";
            else return params;
        }
        @Override
        public int getCount() {
            //每页行数
            return selectJSON.length();
        }
        @Override
        public Object getItem(int position) {
            try {
                if (position<selectJSON.length())
                    return selectJSON.getJSONArray(position);
                else
                    return null;
            } catch (JSONException e)
            {
                e.printStackTrace();
                System.out.println("getItem取JSON数据出错!");
                return  null;
            }
        }
        @Override
        public long getItemId(int position) {
            return position;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = inflater.inflate(R.layout.popselect_item, null, false);
            int pullVatListWidth=parent.getWidth();
            view.setLayoutParams(new ListView.LayoutParams((int)pullVatListWidth,dp2px(45)));
            //转换分页码;
            int curPosition= position;
            String tmpValue;
            int color = getResources().getColor(R.color.text_black);
            if (curPosition<selectJSON.length()) {
                try {
                    Log.d(TAG, "getView()----------------------------------------------------->" + position);
                    if (selectJSON.optJSONObject(curPosition).has("ConColor") == true) {
                        tmpValue = selectJSON.optJSONObject(curPosition).getString("ConColor");
                        color=GetColorValue(tmpValue);
                    }
                    for (int i = 0; i < sizeListHead.length(); i++)
                        if (sizeListHead.optJSONObject(i).has("TitleText") == true) {
                            try {
                                String TitleName = sizeListHead.optJSONObject(i).getString("TitleName");
                                if (selectJSON.optJSONObject(curPosition).has(TitleName)==true) tmpValue= selectJSON.optJSONObject(curPosition).getString(TitleName);
                                else tmpValue="unReturn";
                                int TxtSize = sizeListHead.optJSONObject(i).getInt("TxtSize");
                                float txtWidth = sizeListHead.optJSONObject(i).getLong("TxtWidth");
                                int AutoZoom = sizeListHead.optJSONObject(i).getInt("AutoZoom");
                                TextView tv = new TextView(view.getContext());
                                tv.setText(TrnasValue(tmpValue));
                                tv.setWidth((int) txtWidth);
                                tv.setTextColor(color);
                                tv.setGravity(Gravity.CENTER_VERTICAL);
                                if (sizeListHead.optJSONObject(i).has("Align")==true) {
                                    int Align;
                                    Align = sizeListHead.optJSONObject(i).getInt("Align");
                                    switch (Align) {
                                        case 0:
                                            tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
                                            break;
                                        case 1:
                                            tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
                                            break;
                                        case 2:
                                            tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.RIGHT);
                                            break;
                                        default:
                                            tv.setGravity(Gravity.CENTER_VERTICAL);
                                            break;
                                    }
                                }
                                tv.setTextSize(TxtSize);
                                //添加到View中;
                                if (AutoZoom == 1)
                                    ((LinearLayout)view).addView(tv, new LinearLayout.LayoutParams((int) txtWidth, MATCH_PARENT, 1));
                                else ((LinearLayout)view).addView(tv);
                            } catch (JSONException e) {
                                e.printStackTrace();
                            }
                        }
                } catch (JSONException e) {
                    e.printStackTrace();
                    Toast.makeText(getContext(), e.getMessage(), Toast.LENGTH_SHORT).show();
                }
            }
            return view;
        }
    }


    //从字符串转颜色
    private int GetColorValue(String paramColor){
        int PenColor= Color.WHITE;
        String StrPenColor=paramColor;
        if (StrPenColor.indexOf("#")==0){
            PenColor=Color.parseColor(StrPenColor);
        }else {
            if (isNumeric(StrPenColor)) {
                int testColor = Integer.parseInt(StrPenColor);
                int red = (testColor & 0xff0000) >> 16;
                int green = (testColor & 0x00ff00) >> 8;
                int blue = (testColor & 0x0000ff);
                PenColor = Color.rgb(red, green, blue);
            } else {
                if (StrPenColor.equals("Black") == true)
                    PenColor = Color.BLACK;
                if (StrPenColor.equals("Blue") == true)
                    PenColor = Color.BLUE;
                if (StrPenColor.equals("Yellow") == true)
                    PenColor = Color.YELLOW;
                if (StrPenColor.equals("Red") == true)
                    PenColor = Color.RED;
                if (StrPenColor.equals("Green") == true)
                    PenColor = Color.GREEN;
                if (StrPenColor.equals("Gray") == true)
                    PenColor = Color.LTGRAY;
                if (StrPenColor.equals("White") == true)
                    PenColor = Color.WHITE;
                if (StrPenColor.equals("Main") == true)
                    PenColor = getResources().getColor(R.color.text_main);
            }
        }
        return PenColor;
    }

    //订单表格适配器;
    public final class ModeListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public ModeListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return packModeJSON.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return packModeJSON.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            convertView = inflater.inflate(R.layout.fragment_prepbox_modeitem, null, false);
            try {
                System.out.println("1");
                if (packModeJSON.optJSONObject(position).has("ConColor")){
                    int backcolor=Color.parseColor(packModeJSON.optJSONObject(position).getString("ConColor"));
                    convertView.findViewById(R.id.linerCardBack).setBackgroundColor(backcolor);
                }
                TextView tv = (TextView) convertView.findViewById(R.id.item_boxArea);// 显示文字
                if (packModeJSON.optJSONObject(position).has("BoxArea")) tv.setText(packModeJSON.optJSONObject(position).get("BoxArea").toString());

                System.out.println("2");
                tv = (TextView) convertView.findViewById(R.id.item_totalBox);// 显示文字
                if (packModeJSON.optJSONObject(position).has("TotalBox")) tv.setText(packModeJSON.optJSONObject(position).get("TotalBox").toString());

                System.out.println("3");
                tv = (TextView) convertView.findViewById(R.id.item_packMode);// 显示文字
                if (packModeJSON.optJSONObject(position).has("PackMode")) tv.setText(packModeJSON.optJSONObject(position).get("PackMode").toString());

                System.out.println("4");
                tv = (TextView) convertView.findViewById(R.id.item_readyBox);// 显示文字
                if (packModeJSON.optJSONObject(position).has("ReadyBox")) tv.setText(packModeJSON.optJSONObject(position).get("ReadyBox").toString());


            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }

            return convertView;
        }
    }


    //订单表格适配器;
    public final class BoxListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public BoxListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return boxListJSON.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return boxListJSON.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView==null) convertView = inflater.inflate(R.layout.fragment_prepbox_boxitem, null, false);
            String tmpValue;
            try {
                if (boxListJSON.optJSONObject(position).has("ConColor")){
                    int backcolor=Color.parseColor(boxListJSON.optJSONObject(position).getString("ConColor"));
                    convertView.setBackgroundColor(backcolor);
                }
                TextView tv = (TextView) convertView.findViewById(R.id.txt_item_SerNo);// 显示文字
                if (boxListJSON.optJSONObject(position).has("SerNo")) tv.setText(boxListJSON.optJSONObject(position).get("SerNo").toString());
                tv = (TextView) convertView.findViewById(R.id.txt_item_BoxNo);// 显示文字
                if (boxListJSON.optJSONObject(position).has("BoxNo")) tv.setText(boxListJSON.optJSONObject(position).get("BoxNo").toString());
                tv = (TextView) convertView.findViewById(R.id.txt_item_PO);// 显示文字
                if (boxListJSON.optJSONObject(position).has("PO")) tv.setText(boxListJSON.optJSONObject(position).get("PO").toString());
                tv = (TextView) convertView.findViewById(R.id.txt_item_PO);// 显示文字
                if (boxListJSON.optJSONObject(position).has("PO")) tv.setText(boxListJSON.optJSONObject(position).get("PO").toString());
                tv = (TextView) convertView.findViewById(R.id.txt_item_PO);// 显示文字
                if (boxListJSON.optJSONObject(position).has("PO")) tv.setText(boxListJSON.optJSONObject(position).get("PO").toString());

            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }

            return convertView;
        }
    }

    //订单表格适配器;
    public final class PackListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public PackListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        @Override
        public int getCount() {
            return packListJSON.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                return packListJSON.get(position);
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return null;
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView==null) convertView = inflater.inflate(R.layout.fragment_prepbox_packitem, null, false);
            String tmpValue;
            try {
                if (packListJSON.optJSONObject(position).has("ConColor")){
                    int backcolor=Color.parseColor(packListJSON.optJSONObject(position).getString("ConColor"));
                    convertView.setBackgroundColor(backcolor);
                }
                TextView tv = (TextView) convertView.findViewById(R.id.txt_item_Color);// 显示文字
                if (packListJSON.optJSONObject(position).has("Color")) tv.setText(packListJSON.optJSONObject(position).get("Color").toString());
                tv = (TextView) convertView.findViewById(R.id.txt_item_Size);// 显示文字
                if (packListJSON.optJSONObject(position).has("Size")) tv.setText(packListJSON.optJSONObject(position).get("Size").toString());
                tv = (TextView) convertView.findViewById(R.id.txt_item_NeedNum);// 显示文字
                if (packListJSON.optJSONObject(position).has("NeedNum")) tv.setText(packListJSON.optJSONObject(position).get("NeedNum").toString());
                tv = (TextView) convertView.findViewById(R.id.txt_item_ReadyNum);// 显示文字
                if (packListJSON.optJSONObject(position).has("ReadyNum")) tv.setText(packListJSON.optJSONObject(position).get("ReadyNum").toString());
                tv = (TextView) convertView.findViewById(R.id.txt_item_OwenNum);// 显示文字
                if (packListJSON.optJSONObject(position).has("OwenNum")) tv.setText(packListJSON.optJSONObject(position).get("OwenNum").toString());
            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }

            return convertView;
        }
    }


    private void initPopwindow() {
        selBoxBarcode="";
        popupWindow = new PopupWindow(contentView, -1, -2);
        popupWindow.setFocusable(true);
        contentView.findViewById(R.id.btn_pop_ok).setOnClickListener(new View.OnClickListener() {
            public void onClick(View param1View) {

                if (popupWindow != null && popupWindow.isShowing())
                    popupWindow.dismiss();
            }
        });
        contentView.findViewById(R.id.btn_pop_cancel).setOnClickListener(new View.OnClickListener() {
            public void onClick(View param1View) {
                if (popupWindow != null && popupWindow.isShowing())
                    popupWindow.dismiss();
            }
        });
        tv_pop_title = (TextView)contentView.findViewById(R.id.tv_pop_title);
        lv_Detail = (ListView)contentView.findViewById(R.id.lv_Detail);
        templetlisthead = (LinearLayout)contentView.findViewById(R.id.templetlisthead);
        popupWindow.setBackgroundDrawable((Drawable)new BitmapDrawable());
        popupWindow.setOutsideTouchable(true);
        popupWindow.setTouchable(true);
        popupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);
    }


    //清除界面显示内容
    private void clearFormText(){
        txt_BoxBarcode.setText("");
        txt_OrderNo.setText("");
        txt_StyleNo.setText("");
        txt_PO.setText("");
        txt_Item.setText("");
        txt_hintinfo.setText("");
        txt_NeedNum.setText("");
        txt_PackMode.setText("");
        txt_BoxArea.setText("");
        txt_PackNum.setText("");
        txt_IronNum.setText("");
    }

    //填充界面显示内容;
    private void fillFormtext(){
        if (resultJSON.length()>0)
        {
            try {
                if (resultJSON.getJSONObject(0).has("ClearScreen")==true) {
                    if (resultJSON.getJSONObject(0).getString("ClearScreen").equals("Y")) clearFormText();
                }
                if (resultJSON.getJSONObject(0).has("TaskID")==true) selTaskID=resultJSON.getJSONObject(0).getString("TaskID");
                if (resultJSON.getJSONObject(0).has("BasketID")==true) selBasketID=resultJSON.getJSONObject(0).getString("BasketID");
                if (resultJSON.getJSONObject(0).has("Color")==true) {
                    selColor=resultJSON.getJSONObject(0).getString("Color");
                    txt_Color.setText(resultJSON.getJSONObject(0).getString("Color"));
                }
                if (resultJSON.getJSONObject(0).has("Size")==true) selSize=resultJSON.getJSONObject(0).getString("Size");
                if (resultJSON.getJSONObject(0).has("ClearStyleSort")==true) txt_StyleSort.setText("");;
                if (resultJSON.getJSONObject(0).has("StyleSort")==true) {
                    styleSortJSON=new JSONArray("[]");
                    String StyleSort=resultJSON.getJSONObject(0).getString("StyleSort");
                    String[] list=StyleSort.split(";");
                    if (list.length==1){
                        txt_StyleSort.setText(list[0]);
                    } else{
                        for (int i=0;i<list.length;i++){
                            JSONObject jsonObject=new JSONObject();
                            jsonObject.put("StyleSort",list[i]);
                            styleSortJSON.put(jsonObject);
                        }
                    }
                }
                if (resultJSON.getJSONObject(0).has("GetPackList")==true) {
                    if (resultJSON.getJSONObject(0).getString("GetPackList").equals("Y")){
                        GetPackList();
                    }
                } else
                if (resultJSON.getJSONObject(0).has("ReadyNums")&&resultJSON.getJSONObject(0).has("UnReadyNums")){
                    String ReadyNums=resultJSON.getJSONObject(0).getString("ReadyNums");
                    String UnReadyNums=resultJSON.getJSONObject(0).getString("UnReadyNums");
                    String[] listReady=ReadyNums.split(";");
                    String[] listUnReady=UnReadyNums.split(";");
                    root.findViewById(R.id.linearStyle1).setVisibility(View.GONE);
                    root.findViewById(R.id.linearStyle2).setVisibility(View.GONE);
                    root.findViewById(R.id.linearStyle3).setVisibility(View.GONE);
                    if (listReady.length>=1&&listUnReady.length>=1){
                        root.findViewById(R.id.linearStyle1).setVisibility(View.VISIBLE);
                        ((TextView)root.findViewById(R.id.txt_ReadyNum1)).setText(listReady[0]);
                        ((TextView)root.findViewById(R.id.txt_UnReadyNum1)).setText(listUnReady[0]);
                    }
                    if (listReady.length>=2&&listUnReady.length>=2){
                        root.findViewById(R.id.linearStyle2).setVisibility(View.VISIBLE);
                        ((TextView)root.findViewById(R.id.txt_ReadyNum2)).setText(listReady[1]);
                        ((TextView)root.findViewById(R.id.txt_UnReadyNum2)).setText(listUnReady[1]);
                    }
                    if (listReady.length>=3&&listUnReady.length>=3){
                        root.findViewById(R.id.linearStyle3).setVisibility(View.VISIBLE);
                        ((TextView)root.findViewById(R.id.txt_ReadyNum3)).setText(listReady[2]);
                        ((TextView)root.findViewById(R.id.txt_UnReadyNum3)).setText(listUnReady[2]);
                    }
                }
                if (resultJSON.getJSONObject(0).has("BoxBarcode")==true) txt_BoxBarcode.setText(resultJSON.getJSONObject(0).getString("BoxBarcode"));
                System.out.println("1");
                if (resultJSON.getJSONObject(0).has("OrderNo")==true) txt_OrderNo.setText(resultJSON.getJSONObject(0).getString("OrderNo"));
                if (resultJSON.getJSONObject(0).has("StyleNo")==true) txt_StyleNo.setText(resultJSON.getJSONObject(0).getString("StyleNo"));
                if (resultJSON.getJSONObject(0).has("PO")==true) txt_PO.setText(resultJSON.getJSONObject(0).getString("PO"));
                System.out.println("2");
                if (resultJSON.getJSONObject(0).has("BoxArea")==true) txt_BoxArea.setText(resultJSON.getJSONObject(0).getString("BoxArea"));
                if (resultJSON.getJSONObject(0).has("NeedNum")==true) txt_NeedNum.setText(resultJSON.getJSONObject(0).getString("NeedNum"));
                if (resultJSON.getJSONObject(0).has("PackMode")==true) txt_PackMode.setText(resultJSON.getJSONObject(0).getString("PackMode"));
                if (resultJSON.getJSONObject(0).has("UnReadyNum")==true) txt_UnReadyNum.setText(resultJSON.getJSONObject(0).getString("UnReadyNum"));
                System.out.println("3");
                if (resultJSON.getJSONObject(0).has("Item")==true) txt_Item.setText(resultJSON.getJSONObject(0).getString("Item"));
                if (resultJSON.getJSONObject(0).has("IronNum")==true) txt_IronNum.setText(resultJSON.getJSONObject(0).getString("IronNum"));
                if (resultJSON.getJSONObject(0).has("PackNum")==true) txt_PackNum.setText(resultJSON.getJSONObject(0).getString("PackNum"));
                if (resultJSON.getJSONObject(0).has("OwenNum")==true) txt_OwenNum.setText(resultJSON.getJSONObject(0).getString("OwenNum"));

                System.out.println("4");
                if (resultJSON.getJSONObject(0).has("SpeakText")==true){
                    if (resultJSON.getJSONObject(0).getString("SpeakText").length()>0) {
                        if (mFragmentPrepBoxCallBack != null) {
                            fragmentParams.clear();
                            fragmentParams.put("ParamComm", "TTS");//命令;
                            fragmentParams.put("ParamValue", resultJSON.getJSONObject(0).getString("SpeakText"));//参数;
                            mFragmentPrepBoxCallBack.FragmentPrepBoxWorkAndTransParams(fragmentParams);
                        } else Log.d("msg", "mFragmentECallBack-----------空的咋办");
                    }
                }
                if (resultJSON.getJSONObject(0).has("hintinfo")==true) txt_hintinfo.setText(resultJSON.getJSONObject(0).getString("hintinfo"));
                if (resultJSON.getJSONObject(0).has("ErrInfo")==true)
                {
                    MediaPlayer mediaPlayer = MediaPlayer.create(getActivity(),R.raw.warn);
                    mediaPlayer.start();
                    AlertDialog alertDialog = new AlertDialog.Builder(getActivity())
                            .setTitle("系统提示").setMessage(resultJSON.getJSONObject(0).getString("ErrInfo"))
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int which) {
                                    return;
                                }
                            }).create(); // 创建对话框
                    alertDialog.show(); // 显示对话框
                }
                if (resultJSON.getJSONObject(0).has("GetPackMode")==true) {
                    if (resultJSON.getJSONObject(0).getString("GetPackMode").equals("Y")){
                        GetPackMode();
                    }
                } else if (resultJSON.getJSONObject(0).has("GetBoxList")==true) {
                    if (resultJSON.getJSONObject(0).getString("GetBoxList").equals("Y")){
                        GetBoxList();
                    }
                } else
                if (resultJSON.getJSONObject(0).has("PlayWarn")==true){
                    if (resultJSON.getJSONObject(0).getString("PlayWarn").equals("Y")){
                        playRingWarn();
                    }
                }

                if (resultJSON.getJSONObject(0).has("InputBoxPiece")==true)
                {
                    showBoxPiece();
                }
                if (resultJSON.getJSONObject(0).has("GetSizeList")==true)
                {
                    if (resultJSON.getJSONObject(0).getString("GetSizeList").equals("Y"))
                        GetSizeList("SizeListHead");
                }

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
        System.out.println("fillFormtext----------edt_barcode置焦点");

    }


    //修改包件数;
    private void showBoxPiece(){
        //    通过LayoutInflater来加载一个xml的布局文件作为一个View对象
        View view = LayoutInflater.from(getContext()).inflate(R.layout.input_num_piece, null);
        popupWindow = new PopupWindow(view,200,300);//参数为1.View 2.宽度 3.高度
        popupWindow.setTouchable(true);
        popupWindow.setOutsideTouchable(true);//设置点击外部区域可以取消popupWindow
        popupWindow.setAnimationStyle(R.style.mypopwindow_anim_style);
        edt_checkReal=view.findViewById(R.id.edt_number);
        view.findViewById(R.id.view_oneBtn).setOnClickListener(this);
        view.findViewById(R.id.view_twoBtn).setOnClickListener(this);
        view.findViewById(R.id.view_threeBtn).setOnClickListener(this);
        view.findViewById(R.id.view_fourBtn).setOnClickListener(this);
        view.findViewById(R.id.view_fiveBtn).setOnClickListener(this);
        view.findViewById(R.id.view_sixBtn).setOnClickListener(this);
        view.findViewById(R.id.view_sevenBtn).setOnClickListener(this);
        view.findViewById(R.id.view_eightBtn).setOnClickListener(this);
        view.findViewById(R.id.view_nineBtn).setOnClickListener(this);
        view.findViewById(R.id.view_zeroBtn).setOnClickListener(this);
        view.findViewById(R.id.view_delBtn).setOnClickListener(this);
        view.findViewById(R.id.view_clearBtn).setOnClickListener(this);
        view.findViewById(R.id.btn_AffirmCall).setOnClickListener(this);
        //控制屏幕宽度
        int deviationX=500,deviationY=370;
        DisplayMetrics dm = new DisplayMetrics();
        popupWindow.setWidth(dp2px(deviationX));
        popupWindow.setHeight(dp2px(deviationY));
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.showAtLocation(mainLinerLayout,Gravity.CENTER,0,0);

    }
    //插放音乐;
    private void playRingWarn(){
        Uri notification = Uri.parse("android.resource://"+getActivity().getPackageName()+"/"+R.raw.warn);
        Ringtone r = RingtoneManager.getRingtone(getContext(), notification);
        r.play();

    }
    @Override
    public void onStart() {
        super.onStart();
        //设置焦点
        System.out.println("FragmentmPrepBox 设置焦点-------------------------------1.Start");
        setEditBarcodeFocus();
        System.out.println("FragmentmPrepBox 设置焦点-------------------------------1.End");
        refreshDepartData();

    }

    private void showSelectStyleSort(){
        //先显示对话框,再调用查询加载
        if (styleSortJSON==null||styleSortJSON.length()==0) {
            curToast.setText("没有款式数据!");
            curToast.show();
            return;
        }
        initPopwindow();
        try {
            headJSON = new JSONArray("[{\"TitleName\":\"StyleSort\",\"TitleText\":\"款式\",\"TxtSize\":20,\"TxtWidth\":180,\"AutoZoom\":0,\"Align\":0,\"Color\":\"Main\"}]");
        } catch (JSONException jSONException) {
            jSONException.printStackTrace();
        }
        tv_pop_title.setText("请选择装箱款式");
        contentView.findViewById(R.id.linear_pop_search).setVisibility(GONE);
        contentView.findViewById(R.id.btn_pop_cancel).setVisibility(GONE);
        CreateListHead();
        //准备显示明细
        SelectTempletListAdapter selectTempletListAdapter = new SelectTempletListAdapter(getContext());
        selectTempletListAdapter.selectJSON= styleSortJSON;
        lv_Detail.setAdapter(selectTempletListAdapter);
        lv_Detail.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            public void onItemClick(AdapterView<?> param1AdapterView, View view, int postion, long param1Long) {
                try {
                    txt_StyleSort.setText(styleSortJSON.optJSONObject(postion).getString("StyleSort"));
                    popupWindow.dismiss();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        });
        //控制屏幕宽度
        int deviationX=500,deviationY=500;
        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        System.out.println("屏宽:" + dm.widthPixels);
        System.out.println("屏高:" + dm.heightPixels);
        popupWindow.setWidth(dp2px(deviationX));
        popupWindow.setHeight(dp2px(deviationY));
        popupWindow.showAtLocation(mainLinerLayout, Gravity.CENTER,0,0);
    }


    //创建列;
    private void CreateListHead() {
        System.out.println("CreateListHead()");
        //内容为表头，宽度，自适应;
        if ((headJSON != null) && (headJSON.length() > 0)) {
            int childCount = templetlisthead.getChildCount();
            for (int i = childCount - 1; i >= 0; i--) {
                View view = templetlisthead.getChildAt(i);
                if (view instanceof TextView) {
                    templetlisthead.removeViewAt(i);
                }
            }
            //创建列
            String TitleText,TitleName;
            float  txtWidth;
            int TxtSize,AutoZoom,Align;
            for (int i=0;i<headJSON.length();i++)
                if (headJSON.optJSONObject(i).has("TitleText") == true) {
                    try {
                        System.out.println("CreateListHead()"+i);
                        TitleName = headJSON.optJSONObject(i).getString("TitleName");
                        TitleText = headJSON.optJSONObject(i).getString("TitleText");
                        TxtSize = headJSON.optJSONObject(i).getInt("TxtSize");
                        txtWidth = headJSON.optJSONObject(i).getLong("TxtWidth");
                        AutoZoom = headJSON.optJSONObject(i).getInt("AutoZoom");
                        TextView tv = new TextView(getContext());
                        tv.setText(TitleText);
                        tv.setWidth((int) txtWidth);
                        tv.setTextColor(getResources().getColor(R.color.white));
                        tv.setTextSize(TxtSize);
                        if (headJSON.optJSONObject(i).has("Align")==true) {
                            Align = headJSON.optJSONObject(i).getInt("Align");
                            switch (Align) {
                                case 0:
                                    tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
                                    break;
                                case 1:
                                    tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
                                    break;
                                case 2:
                                    tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.RIGHT);
                                    break;
                                default:
                                    tv.setGravity(Gravity.CENTER_VERTICAL);
                                    break;
                            }
                        }
                        //自定义文字颜色;
                        if (headJSON.optJSONObject(i).has("Color")==true){
                            tv.setTextColor(GetColorValue( headJSON.optJSONObject(i).getString("Color")));
                        }
                        //添加到View中;
                        if (AutoZoom==1) templetlisthead.addView(tv,new LinearLayout.LayoutParams((int) txtWidth, MATCH_PARENT, 1));
                        else  templetlisthead.addView(tv,new LinearLayout.LayoutParams((int) txtWidth, MATCH_PARENT, 0));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            templetlisthead.postInvalidate();
        }
    }


    //创建列;
    private void CreateSizeListHead() {
        System.out.println("CreateListHead()");
        //内容为表头，宽度，自适应;
        if ((sizeListHead != null) && (sizeListHead.length() > 0)) {
            int childCount = querylisthead.getChildCount();
            for (int i = childCount - 1; i >= 0; i--) {
                View view = querylisthead.getChildAt(i);
                if (view instanceof TextView) {
                    querylisthead.removeViewAt(i);
                }
            }
            //创建列
            String TitleText,TitleName;
            float  txtWidth;
            int TxtSize,AutoZoom,Align;
            for (int i=0;i<sizeListHead.length();i++)
                if (sizeListHead.optJSONObject(i).has("TitleText") == true) {
                    try {
                        System.out.println("CreateListHead()"+i);
                        TitleName = sizeListHead.optJSONObject(i).getString("TitleName");
                        TitleText = sizeListHead.optJSONObject(i).getString("TitleText");
                        TxtSize = sizeListHead.optJSONObject(i).getInt("TxtSize");
                        txtWidth = sizeListHead.optJSONObject(i).getLong("TxtWidth");
                        AutoZoom = sizeListHead.optJSONObject(i).getInt("AutoZoom");
                        TextView tv = new TextView(getContext());
                        tv.setText(TitleText);
                        tv.setWidth((int) txtWidth);
                        tv.setTextColor(getResources().getColor(R.color.white));
                        tv.setTextSize(TxtSize);
                        if (sizeListHead.optJSONObject(i).has("Align")==true) {
                            Align = sizeListHead.optJSONObject(i).getInt("Align");
                            switch (Align) {
                                case 0:
                                    tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.LEFT);
                                    break;
                                case 1:
                                    tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL);
                                    break;
                                case 2:
                                    tv.setGravity(Gravity.CENTER_VERTICAL | Gravity.RIGHT);
                                    break;
                                default:
                                    tv.setGravity(Gravity.CENTER_VERTICAL);
                                    break;
                            }
                        }
                        //自定义文字颜色;
                        if (sizeListHead.optJSONObject(i).has("Color")==true){
                            tv.setTextColor(GetColorValue( sizeListHead.optJSONObject(i).getString("Color")));
                        }
                        //自定义背景颜色;
                        if (sizeListHead.optJSONObject(i).has("TitleColor")==true){
                            tv.setBackgroundColor(GetColorValue( sizeListHead.optJSONObject(i).getString("TitleColor")));
                        }
                        //添加到View中;
                        if (AutoZoom==1) querylisthead.addView(tv,new LinearLayout.LayoutParams((int) txtWidth, MATCH_PARENT, 1));
                        else querylisthead.addView(tv,new LinearLayout.LayoutParams((int) txtWidth, MATCH_PARENT, 0));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            querylisthead.postInvalidate();
        }
    }

    //dp 转换成px
    public int dp2px(float dp)
    {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, getResources().getDisplayMetrics());
    }


    //过滤装箱规则
    private void GetPackMode() {
        //执行SQL过程
        String SqlComm="Exec KeyPoint_Pack_PrepPackMode  @OperType='PackMode',@TermNO='" + curTermNo + "',@ManuWorkGroup='" + edt_WorkGroup.getText().toString()
                + "',@WorkGroup='" + curDepart+ "',@OrderNo='" + txt_OrderNo.getText().toString()
                + "',@StyleNo='" + txt_StyleNo.getText().toString()+ "',@PO='" + txt_PO.getText().toString()+"',@UserNo='"+curLoginUserNo+"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);

    }
    //获取表头，有表头再获取表尾
    private void GetSizeList(String operType) {
        //执行SQL过程
        String SqlComm="Exec KeyPoint_Pack_PrepPackMode  @OperType='"+operType+"',@TermNO='" + curTermNo
                + "',@ManuWorkGroup='" + edt_WorkGroup.getText().toString()
                + "',@WorkGroup='" + curDepart+ "',@OrderNo='" + txt_OrderNo.getText().toString()
                + "',@StyleNo='" + txt_StyleNo.getText().toString()+ "',@StyleSort='" + txt_StyleSort.getText().toString()
                + "',@PO='" + txt_PO.getText().toString()+"',@UserNo='"+curLoginUserNo+"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);

    }

    //过滤装箱
    private void GetBoxList() {
        //执行SQL过程
        String SqlComm="Exec KeyPoint_Pack_PrepBoxList  @OperType='BoxList',@TermNO='" + curTermNo + "',@ManuWorkGroup='" + edt_WorkGroup.getText().toString()
                + "',@WorkGroup='" + curDepart+ "',@OrderNo='" + txt_OrderNo.getText().toString()
                + "',@StyleNo='" + txt_StyleNo.getText().toString()+ "',@PO='" + txt_PO.getText().toString()+"',@UserNo='"+curLoginUserNo+"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);

    }
    private void GetPackList() {
        //执行SQL过程
        String SqlComm="Exec KeyPoint_Pack_PrepPackList  @OperType='PackList',@TermNO='" + curTermNo + "',@ManuWorkGroup='" + edt_WorkGroup.getText().toString()
                + "',@WorkGroup='" + curDepart+ "',@OrderNo='" + txt_OrderNo.getText().toString()
                + "',@StyleNo='" + txt_StyleNo.getText().toString()+ "',@PO='" + txt_PO.getText().toString()+ "',@BoxBarcode='" + txt_BoxBarcode.getText().toString()+"',@UserNo='"+curLoginUserNo+"'";
        //调用WebService过程并处理界面更新;
        ReadSQLData(SqlComm);

    }


}
